package com.syb.dao.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.syb.dao.RoleDao;
import com.syb.entity.function.SysRole;
import com.syb.util.BaseDao;
import com.syb.util.PageResults;

@Repository
public class RoleDaoImpl extends BaseDao implements RoleDao {

	public List<SysRole> findSysRoleList(PageResults<SysRole> page) throws Exception {
		List<SysRole> sysRole = new ArrayList<SysRole>();
		List<Object> paramList = new ArrayList<Object>(); 
		StringBuffer sub = new StringBuffer();
		sub.append(" select * from sys_role where 1=1 ");
		if(page.getParamMap().get("name")!=null && !("").equals(page.getParamMap().get("name"))){
			sub.append(" and role_name like  ?  ");
			paramList.add("%"+page.getParamMap().get("name")+"%");
		}
		sub.append(" limit ?,?");
		paramList.add(page.getCurrentPage());
		paramList.add(page.getPageSize());
		String sql = sub.toString();
		try{
			Query query = getSessionFactory().getCurrentSession().createSQLQuery(sql).addEntity(SysRole.class);
			if(paramList.size()>0){
				for(int i = 0;i<paramList.size();i++){
					query.setParameter(i, paramList.get(i));
				}
			}
			sysRole = (List<SysRole>)query.list();
		}catch(Exception e){
			throw new Exception(e.getMessage());
		}
		return sysRole;
	}

	public int findSysRoleCount(PageResults<SysRole> page) throws Exception {
		List<BigInteger> sysRole = new ArrayList<BigInteger>();
		List<Object> paramList = new ArrayList<Object>(); 
		StringBuffer sub = new StringBuffer();
		sub.append(" select count(*) from sys_role where 1=1 ");
		if(page.getParamMap().get("name")!=null && !("").equals(page.getParamMap().get("name"))){
			sub.append(" and role_name like  ?  ");
			paramList.add("%"+page.getParamMap().get("name")+"%");
		}
		String sql = sub.toString();
		try{
			Query query = getSessionFactory().getCurrentSession().createSQLQuery(sql);
			if(paramList.size()>0){
				for(int i = 0;i<paramList.size();i++){
					query.setParameter(i, paramList.get(i));
				}
			}
			sysRole = (List<BigInteger>)query.list();
		}catch(Exception e){
			throw new Exception(e.getMessage());
		}
		return sysRole.get(0).intValue();
	}

}
